<template>
  <div class="view-fill">
    <div class="app-container-flex">
      <full-screen
        v-model="showDialog"
        :title="title"
        :btnList="props.flowFormType ? [] : fullInfo.btnList"
        :needReturn="props.flowFormType ? false : true"
        @returnBack="returnBack"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.baseRef"
              :data="formInfo.data"
              :field-list="formInfo.baseInfoFieldList"
              :rules="formInfo.baseInfoRules"
              :label-width="formInfo.labelWidth"
              @handleEvent="handleEventFrom"
            >
              <template v-slot:form-repairDeptName>
                <el-input
                  v-model="formInfo.data.repairDeptName"
                  type="input"
                  :disabled="true"
                  :class="'not-mongolia'"
                  placeholder="请选择使用部门"
                >
                  <template #append>
                    <el-icon @click="openRepairDeptWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>报修信息</p>
          </div>
          <div class="model-panel-body">
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.repairRef"
              :data="formInfo.data"
              :field-list="formInfo.repairInfoFieldList"
              :rules="formInfo.repairInfoRules"
              :label-width="formInfo.labelWidth"
              @handleEvent="handleEventFrom"
            >
              <template v-slot:form-assetName>
                <el-input
                  type="input"
                  :disabled="formInfo.repairInfoSlot.assetName.disabled"
                  class="not-mongolia"
                  :placeholder="formInfo.repairInfoSlot.assetName.placeholder"
                  maxlength="200"
                  v-model="formInfo.data.assetName"
                >
                  <template
                    #append
                    v-if="formInfo.repairInfoSlot.assetName.disabled"
                  >
                    <el-icon @click="openEquipmentWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>

              <template v-slot:form-useDeptName>
                <el-input
                  type="input"
                  :disabled="formInfo.repairInfoSlot.useDeptName.disabled"
                  class="not-mongolia"
                  :placeholder="formInfo.repairInfoSlot.useDeptName.placeholder"
                  v-model="formInfo.data.useDeptName"
                >
                  <template #append>
                    <el-icon @click="openUsedeptWindow"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-depotName>
                <el-input
                  type="input"
                  :disabled="formInfo.repairInfoSlot.depotName.disabled"
                  class="not-mongolia"
                  :placeholder="formInfo.repairInfoSlot.depotName.placeholder"
                  v-model="formInfo.data.depotName"
                >
                  <template #append>
                    <el-icon @click="openDepotNameWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-faultTime>
                <el-date-picker
                  v-model="formInfo.data.faultTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="faultTimePickerOptions.disabledDate"
                  placeholder="请选择故障发生时间"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-expectCompleteTime>
                <el-date-picker
                  v-model="formInfo.data.expectCompleteTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :disabled-date="expectCompleteTimePickerOptions.disabledDate"
                  placeholder="请选择期望完成时间"
                >
                </el-date-picker>
              </template>
              <template v-slot:form-maintenanceName>
                <el-input
                  type="input"
                  :disabled="true"
                  :class="disabledMaintenanceName ? '' : 'not-mongolia'"
                  placeholder="请选择维保商"
                  v-model="formInfo.data.maintenanceName"
                >
                  <template #append>
                    <el-icon @click="openMaintenanceProviderWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-maintenanceUserName>
                <el-input
                  v-model="formInfo.data.maintenanceUserName"
                  type="input"
                  :disabled="true"
                  class="not-mongolia"
                  placeholder="请选择维保联系人"
                >
                  <template #append>
                    <el-icon @click="openMaintenanceContactsList"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-faultPart>
                <el-input
                  v-model="formInfo.data.faultPart"
                  type="input"
                  class="not-mongolia"
                  placeholder="请输入/选择故障部位"
                >
                  <template #append>
                    <el-icon @click="openAssetResource"><MoreFilled /></el-icon>
                  </template>
                </el-input>
              </template>
              <template v-slot:form-faultDescribe>
                <el-input
                  :style="{
                    width: $permission('repairOrder:selectFaultLib')
                      ? '86%'
                      : '100%',
                  }"
                  v-model="formInfo.data.faultDescribe"
                  type="textarea"
                  :rows="1"
                  :maxlength="500"
                  class="not-mongolia"
                  placeholder="请输入故障描述"
                >
                </el-input>
                <el-tooltip
                  v-if="$permission('repairOrder:selectFaultLib')"
                  effect="dark"
                  content="从故障库选择"
                  placement="top-start"
                >
                  <el-icon
                    style="font-size: 20px; cursor: pointer"
                    @click="openFault"
                    ><CirclePlus
                  /></el-icon>
                </el-tooltip>
              </template>
              <template v-slot:form-filePathList>
                <UploadVideo
                  v-model="formInfo.data.filePathList"
                  :action="action"
                  :fileData="formInfo.data.filePathList"
                  @upload="upload"
                />
              </template>
              <template v-slot:form-classifyTypeValue>
                <el-input
                  v-model="formInfo.data.classifyTypeValue"
                  type="input"
                  :class="formInfo.data.repairType == '1' ? '' : 'not-mongolia'"
                  :disabled="true"
                  placeholder="请选择资产分类"
                >
                  <template #append v-if="formInfo.data.repairType != '1'">
                    <el-icon @click="openAssetClassifyWindow"
                      ><MoreFilled
                    /></el-icon>
                  </template>
                </el-input>
              </template>
            </page-form>
          </div>
        </div>
      </full-screen>
    </div>

    <!--资产选择-->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :highlightRow="true"
      :checkBox="false"
      :tableKey="selectAssetInfo.tableKey"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      @callback="callBackAsset"
    />
    <!-- 维保商 -->
    <select-maintenance
      v-if="selectMaintenanceProvider.visible"
      v-model:show-dialog="selectMaintenanceProvider.visible"
      :query="selectMaintenanceProvider.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectMaintenanceProviderCallback"
    />
    <Select-fault
      v-if="seelctFault.visible"
      v-model:show-dialog="seelctFault.visible"
      :query="seelctFault.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      @callback="selectFaultCallback"
    />
    <!-- 维保联系人 -->
    <Select-users
      v-if="selectMaintenanceContactsInfo.visible"
      v-model:showDialog="selectMaintenanceContactsInfo.visible"
      :api="selectMaintenanceContactsInfo.api"
      :saveEmpty="true"
      :query="selectMaintenanceContactsInfo.query"
      :check-box="false"
      :highlight-row="true"
      :title="selectMaintenanceContactsInfo.title"
      :showPermission="formInfo.data.maintainChannel == 2 ? true : false"
      @callback="selectMaintenanceContactsCallBack"
    />
    <select-dept
      v-if="selectDeptInfo.visible"
      v-model:show-dialog="selectDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDeptInfo.query"
      :save-empty="true"
      :api="getDeptsSelectPageAndMaintenanceGroup"
      @callback="selectDeptCallBack"
    />
    <select-dept
      v-if="selectRepairDeptInfo.visible"
      v-model:show-dialog="selectRepairDeptInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectRepairDeptInfo.query"
      :save-empty="true"
      @callback="selectRepairDeptCallBack"
    />
    <select-depot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDepotInfo.query"
      :save-empty="true"
      :api="getDepotsSelectPageAndMaintenanceGroup"
      @callback="selectDepotCallBack"
    />
    <SelectAssetClassify
      v-if="selectAssetClassifyInfo.visible"
      v-model:showDialog="selectAssetClassifyInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectAssetClassifyInfoCallBack"
    />
    <SelectAssetResource
      v-if="selectAssetResourceInfo.visible"
      v-model:showDialog="selectAssetResourceInfo.visible"
      :query="selectAssetResourceInfo.query"
      :saveEmpty="true"
      :check-box="true"
      :highlight-row="false"
      @callback="SelectAssetResourceCallBack"
    />
  </div>
</template>

<script setup name="repairRepairManageRepairOrderModify">
import {
  createRepairOrder,
  getRepairOrderById,
  updateRepairOrder,
  submitRepairOrder,
  getMaintenanceGroupUserCheckAll,
  getMaintenanceGroupsUserPage,
  getSelectUserWithPermission,
  getMaintenanceGroupUserPage,
  getPageRepairUserListAll,
} from '@/api/repair'
import { getRrgUserList } from '@/api/base.js'
import {
  getDepotsSelectPageAndMaintenanceGroup,
  getDeptsSelectPageAndMaintenanceGroup,
} from '@/api/core.js'

import PageForm from '@/components/PageForm/index'
import FullScreen from '@/components/FullScreen/index'
import SelectUsers from '@/components/SelectUsers/selectMaintenanceUsers'
import UploadVideo from '@/components/UploadVideo/index'
import SelectMaintenance from '@/components/SelectMaintenance/index'
import selectAsset from '@/components/SelectAsset/index'
import _ from 'lodash'
import moment from 'moment'
import axios from 'axios'
import SelectDept from '@/components/SelectDept/index'
import SelectDepot from '@/components/SelectDepot/index'
import SelectAssetClassify from '@/components/SelectAssetClassify/index'

const { proxy } = getCurrentInstance()
const emit = defineEmits()
const router = useRouter()

const props = defineProps(['visible', 'title', 'id', 'type', 'flowFormType'])

let validateFaultTime = (rule, value, callback) => {
  let expectCompleteTime = formInfo.data.expectCompleteTime
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

  if (expectCompleteTime) {
    if (expectCompleteTime < value) {
      callback(new Error('故障发生时间不能大于期望完成时间！'))
    } else if (value > currentTime) {
      callback(new Error('故障时间不能大于当前时间！'))
    } else {
      callback()
    }
  } else {
    if (value > currentTime) {
      callback(new Error('故障时间不能大于当前时间！'))
    } else {
      callback()
    }
  }
}
let validateExpectCompleteTime = (rule, value, callback) => {
  let faultTime = formInfo.data.faultTime
  let currentTime = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

  if (faultTime) {
    if (faultTime > value) {
      callback(new Error('期望完成时间不能小于故障发生时间！'))
    } else if (value < currentTime) {
      callback(new Error('期望完成时间不能小于当前时间！'))
    } else {
      callback()
    }
  } else {
    if (value < currentTime) {
      callback(new Error('期望完成时间不能小于当前时间！'))
    } else {
      callback()
    }
  }
}

const action = ref(axios.defaults.baseURL + '/pub/uploadfile')
const options = ref([])
const formRefs = ref('')
const faultTimePickerOptions = ref({})
const expectCompleteTimePickerOptions = ref({})
const selectMaintenanceProvider = reactive({
  visible: false,
  query: {},
})
const seelctFault = ref({
  visible: false,
  query: {},
})
const selectAssetClassifyInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {},
})
const selectMaintenanceContactsInfo = reactive({
  title: '选择维保联系人',
  visible: false,
  saveEmpty: true,
  api: getSelectUserWithPermission,
  query: {
    orgId: '',
    assetId: '',
    deptId: '',
    depotId: '',
    assetClassifyId: '',
    notAssetRepairType: '',
  },
})
const selectAssetResourceInfo = ref({
  visible: false,
  query: {
    assetId: '',
  },
})
const formInfo = reactive({
  baseRef: null,
  repairRef: null,
  data: {
    repairUser: proxy.$store.state.user.userInfo.user.id
      ? proxy.$store.state.user.userInfo.user.id
      : '',
    repairUserName: proxy.$store.state.user.userInfo.user.name
      ? proxy.$store.state.user.userInfo.user.name
      : '',

    repairDeptId: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.id
      : '',
    repairDeptName: proxy.$store.state.user.userInfo.dept
      ? proxy.$store.state.user.userInfo.dept.name
      : '',
    repairUserTel: proxy.$store.state.user.userInfo.user.tel
      ? proxy.$store.state.user.userInfo.user.tel
      : '',
    filePathList: [],
  },
  formDisabled: false,
  delFiledList: [],
  baseInfoFieldList: [
    {
      label: '报修人',
      value: 'repairUserName',
      type: 'input',
      disabled: true,
    },
    {
      label: '报修人电话',
      value: 'repairUserTel',
      type: 'input',
    },
    {
      label: '报修部门',
      value: 'repairDeptName',
      type: 'slot',
    },
    {
      label: '维修渠道',
      value: 'maintainChannel',
      type: 'select-model',
      code: 'maintain_channel',
      show: true,
      event: 'changeMaintainChannel',
    },
    {
      label: '院区',
      value: 'hospitalArea',
      type: 'select-model',
      code: 'repair_hospital_area',
      show: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  baseInfoRules: {
    repairUserTel: [
      {
        validator: proxy.$validate.cellphone,
        message: '请输入报修人电话',
        trigger: 'blur',
      },
    ],
    repairDeptName: [
      {
        required: true,
        message: '请选择报修部门',
        trigger: 'blur',
      },
    ],
    hospitalArea: [
      {
        required: true,
        message: '请选择院区',
        trigger: 'change',
      },
    ],
  },
  repairInfoFieldList: [
    {
      label: '报修类型',
      value: 'repairType',
      type: 'select-model',
      code: 'repair_type_enum',
      show: true,
      required: true,
      event: 'changeRepairType',
    },
    {
      label: '资产',
      value: 'assetName',
      type: 'slot',
      required: true,
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'input',
      show: true,
      disabled: true,
    },
    {
      label: '资产分类',
      value: 'classifyTypeValue',
      type: 'slot',
      show: true,
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'slot',
      show: true,
      disabled: true,
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'slot',
      show: false,
      disabled: true,
    },
    {
      label: '维修类别',
      value: 'notAssetRepairType',
      type: 'select-model',
      checkDefault: false,
      code: 'not_asset_repair_type',
      clearable: true,
      show: false,
    },
    {
      label: '资产位置',
      value: 'location',
      type: 'input',
    },
    {
      label: '紧急程度',
      value: 'urgencyDegree',
      type: 'radio-model',
      code: 'urgency_degree',
    },
    {
      label: '是否停机',
      value: 'isHalt',
      type: 'radio-model',
      code: 'yes_or_no',
    },
    {
      label: '是否医疗设备',
      value: 'isMedicalEquipment',
      type: 'radio-model',
      code: 'default_no_or_yes',
    },
    {
      label: '故障部位',
      value: 'faultPart',
      type: 'slot',
    },
    {
      label: '故障发生时间',
      value: 'faultTime',
      type: 'slot',
    },
    {
      label: '期望完成时间',
      value: 'expectCompleteTime',
      type: 'slot',
    },
    {
      label: '维保商',
      value: 'maintenanceName',
      type: 'slot',
      show: false,
      required: true,
    },
    {
      label: '维保联系人',
      value: 'maintenanceUserName',
      type: 'slot',
      // show: false,
      required: true,
    },
    {
      label: '维保联系人电话',
      value: 'maintenanceUserTel',
      type: 'input',
    },
    {
      label: '故障描述',
      value: 'faultDescribe',
      type: 'slot',
      maxlength: 500,
      required: true,
    },
    {
      label: '故障图片/语音',
      value: 'filePathList',
      type: 'slot',
      className: 'not-br',
    },
  ],
  repairInfoRules: {
    classifyTypeValue: [
      {
        required: false,
        message: '请选择资产分类',
        trigger: 'change',
      },
    ],
    repairType: [
      {
        required: true,
        message: '请选择报修类型',
        trigger: 'change',
      },
    ],
    assetName: [
      {
        required: true,
        message: '请选择资产',
        trigger: 'blur',
      },
    ],
    location: [
      {
        required: true,
        message: '请输入资产位置',
        trigger: 'blur',
      },
    ],
    faultDescribe: [
      {
        required: true,
        message: '请输入故障描述',
        trigger: 'blur',
      },
    ],
    maintenanceName: [
      {
        required: true,
        message: '请选择维保商',
        trigger: 'blur',
      },
    ],
    maintenanceUserTel: [
      {
        validator: proxy.$validate.cellphone,
        message: '请输入维保联系人电话',
        trigger: 'blur',
      },
    ],
    faultTime: [
      {
        validator: validateFaultTime,
        trigger: 'blur',
      },
    ],
    expectCompleteTime: [
      {
        validator: validateExpectCompleteTime,
        trigger: 'blur',
      },
    ],
    notAssetRepairType: [
      {
        required: true,
        message: '请选择维修类别',
        trigger: 'change',
      },
    ],
    useDeptName: [
      {
        required: false,
        message: '请选择使用部门',
        trigger: 'change',
      },
    ],
  },
  repairInfoSlot: {
    assetName: {
      disabled: true,
      placeholder: '请输入资产',
    },
    useDeptName: {
      disabled: true,
      placeholder: '请选择使用部门',
    },
    depotName: {
      disabled: true,
      placeholder: '请选择仓库',
    },
  },
  labelWidth: '124px',
})
const fullInfo = ref({
  btnList: [
    { label: '保存', event: save, show: proxy.$permission('repairOrder:save') },
    { label: '保存并提交', event: saveAndSubmit, show: proxy.$permission('repairOrder:saveAndSubmit') },
  ],
})
//通过资产档案新增
const selectAssetInfo = reactive({
  visible: false,
  tableKey: 'repairAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO',
  query: {
    queryMap: {
      // id: {
      //   queryType: "NOT_IN",
      //   queryCategory: "AND",
      //   value: "",
      // },
      assetSourceAuth: {
        asTbName: 'core_asset,core_asset',
        columnName: 'use_dept_id,depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'assetSourceAuth',
      },
      status: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '3',
      },
      assetStatus: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '1,3',
      },
      isMaintenance: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 1,
      },
      isLocked: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: 0,
      },
    },
    queryParams: {},
  },
})
const selectDeptInfo = reactive({
  visible: false,
  query: {
    deptAuth: 'id',
  },
})
const selectRepairDeptInfo = reactive({
  visible: false,
  query: {
    // deptAuth: "id",
  },
})
const selectDepotInfo = reactive({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    useTypeId: 2,
    isCargoSpaceManage: 0,
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const disabledMaintenanceName = computed(() => {
  if (
    formInfo.data.assetId &&
    formInfo.data.assetId !== -2 &&
    formInfo.data.maintainChannel == 1
  ) {
    return true
  } else {
    return false
  }
})
watch(
  () => formInfo.data.repairType,
  (val) => {
    if (val == 1) {
      formInfo.repairInfoRules.useDeptName[0].required = false
      formInfo.repairInfoRules.location[0].required = false
      formInfo.repairInfoFieldList.forEach((item) => {
        if (item.value === 'assetName') {
          item.label = '资产'
        }
        if (item.value === 'isMedicalEquipment') {
          item.disabled = true
          formInfo.data.isMedicalEquipment = 0
        }
      })
      let assetName = {
        disabled: true,
        placeholder: '请选择资产',
      }
      let assetNameRule = [
        {
          required: true,
          message: '请选择资产',
          trigger: 'blur',
        },
      ]
      formInfo.repairInfoSlot['assetName'] = assetName
      formInfo.repairInfoRules['assetName'] = assetNameRule
    } else if (val == 2) {
      formInfo.repairInfoRules.useDeptName[0].required = true
      formInfo.repairInfoRules.location[0].required = true
      formInfo.repairInfoFieldList.forEach((item) => {
        if (item.value === 'assetName') {
          item.label = '资产/报修内容'
        }
        if (item.value === 'isMedicalEquipment') {
          item.disabled = false
        }
      })
      let assetName = {
        disabled: false,
        placeholder: '请输入资产\报修内容',
      }
      let assetNameRule = [
        {
          required: true,
          message: '请输入资产\报修内容',
          trigger: 'blur',
        },
      ]
      formInfo.repairInfoSlot['assetName'] = assetName
      formInfo.repairInfoRules['assetName'] = assetNameRule
    }
  }
)
onMounted(() => {
  faultTimePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() > Date.now()
    },
  }
  expectCompleteTimePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() < Date.now() - 8.64e7
    },
  }
  formRefs.value = [formInfo.baseRef, formInfo.repairRef]
  if (props.id) {
    getDetails(props.id)
  } else {
    let maintainChannel =
      proxy.$store.state.permission.dict['maintain_channel'] || []
    if (maintainChannel && maintainChannel.length) {
      let enableArr = maintainChannel.filter((item) => item.isEnable === 1)
      let defaultArr = enableArr.filter((item) => item.isDefault === 1)
      if (defaultArr && defaultArr.length) {
        let obj = defaultArr[0]
        formInfo.data.maintainChannel = obj.code
        formInfo.data.maintainChannelName = obj.name
      } else {
        let obj = enableArr[0]
        formInfo.data.maintainChannel = obj.code
        formInfo.data.maintainChannelName = obj.name
      }
      handleEventFrom('changeMaintainChannel', formInfo.data.maintainChannel)
    }
    let repairTypeEnum =
      proxy.$store.state.permission.dict['repair_type_enum'] || []
    if (repairTypeEnum && repairTypeEnum.length) {
      let enableArr = repairTypeEnum.filter((item) => item.isEnable === 1)
      let defaultArr = enableArr.filter((item) => item.isDefault === 1)
      if (defaultArr && defaultArr.length) {
        let obj = defaultArr[0]
        formInfo.data.repairType = obj.code
        formInfo.data.repairTypeValue = obj.name
      } else {
        let obj = enableArr[0]
        formInfo.data.repairType = obj.code
        formInfo.data.repairTypeValue = obj.name
      }
      handleEventFrom('changeRepairType', formInfo.data.repairType)
    }
  }
})

function getFlowFormInfo() {
  return formInfo.data
}
function openAssetClassifyWindow() {
  if (formInfo.data.repairType == '2') {
    selectAssetClassifyInfo.visible = true
  }
}
function selectAssetClassifyInfoCallBack(row) {
  if (row) {
    formInfo.data['classifyType'] = row.id
    formInfo.data['classifyTypeValue'] = row.name
  } else {
    formInfo.data['classifyType'] = -2
    formInfo.data['classifyTypeValue'] = ''
  }
}
function openRepairDeptWindow() {
  //登陆人员是维修人员，则无deptAuth，否则有deptAuth
  let roleType = proxy.$store.state.user.userInfo.user.id
    ? proxy.$store.state.user.userInfo.user.roleType
    : ''
  if (roleType !== 'maintenanceGroupUser') {
    selectRepairDeptInfo.query = {
      deptAuth: 'id',
    }
  }
  selectRepairDeptInfo.visible = true
}
function selectRepairDeptCallBack(row) {
  if (row && row.id) {
    formInfo.data['repairDeptId'] = row.id
    formInfo.data['repairDeptName'] = row.name
  } else {
    formInfo.data['repairDeptId'] = -2
    formInfo.data['repairDeptName'] = ''
  }
}
function handleEventFrom(event, data) {
  if (event === 'changeMaintainChannel') {
    if (data == 1) {
      //切换院外维修
      //formInfo.repairInfoFieldList[9].show = true;
      showFieldListItem(true, 'maintenanceName')
      //formInfo.repairInfoFieldList[8.show = true;
    } else if (data == 2) {
      //切换院内维修
      showFieldListItem(false, 'maintenanceName')
      //formInfo.repairInfoFieldList[8].show = false;
      //formInfo.repairInfoFieldList[9].show = false;
    }
    formInfo.data['assetName'] = ''
    formInfo.data['assetCode'] = ''
    formInfo.data['assetId'] = ''
    formInfo.data['classifyType'] = -2
    formInfo.data['classifyTypeValue'] = ''
    formInfo.data['useDeptName'] = ''
    formInfo.data['useDeptId'] = ''
    formInfo.data['location'] = ''
    formInfo.data['maintenanceId'] = ''
    formInfo.data['maintenanceName'] = ''
    formInfo.data['maintenanceUser'] = ''
    formInfo.data['maintenanceUserName'] = ''
    formInfo.data['maintenanceUserTel'] = ''
  } else if (event === 'changeRepairType') {
    if (data == '1') {
      showFieldListItem(true, 'assetCode')
      showFieldListItem(true, 'classifyTypeValue')
      showFieldListItem(false, 'notAssetRepairType')
      showFieldListItem(true, 'isHalt')
      showFieldListItem(true, 'faultPart')
      // showFieldListItem(false, 'depotName')
      attrFieldListItem('disabled', true, 'assetCode')
      attrFieldListItem('disabled', true, 'useDeptName')
    } else if (data == '2') {
      showFieldListItem(false, 'assetCode')
      showFieldListItem(false, 'classifyTypeValue')
      showFieldListItem(true, 'notAssetRepairType')
      showFieldListItem(false, 'isHalt')
      showFieldListItem(false, 'faultPart')
      showFieldListItem(true, 'useDeptName')
      // showFieldListItem(true, 'depotName')
      attrFieldListItem('disabled', false, 'assetCode')
      attrFieldListItem('disabled', false, 'useDeptName')
    }
    formInfo.data['useDeptName'] = ''
    formInfo.data['useDeptId'] = -2
    formInfo.data['assetId'] = -2
    formInfo.data['assetName'] = ''
    formInfo.data['assetCode'] = ''
    formInfo.data['isHalt'] = 0
    formInfo.data['faultPart'] = ''
    formInfo.data['depotId'] = -2
    formInfo.data['depotName'] = ''
    formInfo.data['classifyType'] = -2
    formInfo.data['classifyTypeValue'] = ''
    formInfo.data['maintenanceName'] = ''
    formInfo.data['maintenanceId'] = ''
    formInfo.data['maintenanceUserName'] = ''
    formInfo.data['maintenanceUser'] = ''
    formInfo.data['maintenanceUserTel'] = ''
    formInfo.data['notAssetRepairType'] = ''
    formInfo.data['notAssetRepairTypeValue'] = ''
    formInfo.repairInfoFieldList.forEach((item) => {
      if (item.value === 'assetName') {
        item.label = data == '1' ? '资产' : '资产/报修内容'
      }
    })
  }
}
function selectDeptCallBack(row) {
  if (row) {
    formInfo.data['useDeptId'] = row.id
    formInfo.data['useDeptName'] = row.name
    formInfo.data['depotId'] = -2
    formInfo.data['depotName'] = ''
  } else {
    formInfo.data['useDeptId'] = -2
    formInfo.data['useDeptName'] = ''
  }
}
function selectDepotCallBack(row) {
  if (row && row.id) {
    formInfo.data['depotId'] = row.id
    formInfo.data['depotName'] = row.name
    formInfo.data['useDeptId'] = -2
    formInfo.data['useDeptName'] = ''
  } else {
    formInfo.data['depotId'] = -2
    formInfo.data['depotName'] = ''
  }
}
//故障图片/语音
function upload(data) {
  formInfo.data.filePathList = data
}
function callBackAsset(data) {
  selectAssetInfo.visible = false
  if (data) {
    formInfo.data['assetName'] = data.assetName
    formInfo.data['assetId'] = data.id
    formInfo.data['assetCode'] = data.assetCode
    formInfo.data['classifyType'] = data.classifyType
    formInfo.data['classifyTypeValue'] = data.classifyTypeValue
    formInfo.data['isMedicalEquipment'] = data.isMedicalEquipment
    if (data.assetStatus === 1) {
      formInfo.data['useDeptName'] = data.useDeptNameRate
      formInfo.data['useDeptId'] = -2
      formInfo.data['depotName'] = ''
      formInfo.data['depotId'] = ''
      showFieldListItem(true, 'useDeptName')
      showFieldListItem(false, 'depotName')
    } else if (data.assetStatus === 3) {
      formInfo.data['depotName'] = data.depotName
      formInfo.data['depotId'] = data.depotId
      formInfo.data['useDeptName'] = data.useDeptNameRate
      formInfo.data['useDeptId'] = -2
      showFieldListItem(false, 'useDeptName')
      showFieldListItem(true, 'depotName')
    }
    formInfo.data['location'] = data.location
    if (formInfo.data.maintainChannel == 1) {
      if (data.maintenanceProvider && data.maintenanceProvider != -2) {
        //院外维修
        formInfo.data['maintenanceName'] = data.maintenanceProviderName || ''
        formInfo.data['maintenanceId'] =
          data.maintenanceProvider === -2 ? '' : data.maintenanceProvider
        formInfo.data['maintenanceUserName'] = data.maintenanceContactsName
        formInfo.data['maintenanceUser'] = data.maintenanceContacts
        formInfo.data['maintenanceUserTel'] = data.maintenancePhone
      }
      if (!formInfo.data.maintenanceName) {
        proxy.$message.warning(
          '该设备未配置维保商，无法进行平台报修，请选择院内维修或联系管理人员添加维保商！'
        )
        return
      }
    } else if (formInfo.data.maintainChannel == 2) {
      //院内维修
      formInfo.data['maintenanceUserName'] = data.hospitalMaintainerUserName
      formInfo.data['maintenanceUser'] = data.hospitalMaintainerUser
      formInfo.data['maintenanceUserTel'] = data.hospitalMaintainerPhone
      formInfo.data['maintenanceName'] = ''
      formInfo.data['maintenanceId'] = ''
    }
    // 生命支持 紧急程度为紧急
    if (data.assetMark.includes(4)) {
      formInfo.data['urgencyDegree'] = 2
    } else {
      formInfo.data['urgencyDegree'] = 1
    }
  }
}
function showFieldListItem(show, nameValue) {
  let fieldList = formInfo.repairInfoFieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
function attrFieldListItem(attr, attrVal, nameValue) {
  let fieldList = formInfo.repairInfoFieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item[attr] = attrVal
    }
  })
}

function showBaseFieldListItem(show, nameValue) {
  let fieldList = formInfo.baseInfoFieldList
  fieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
//资产资产
function openEquipmentWindow() {
  if (formInfo.repairInfoSlot.assetName.disabled) {
    selectAssetInfo.visible = true
  }
}
// 使用部门
function openUsedeptWindow() {
  if (
    formInfo.repairInfoSlot.useDeptName.disabled &&
    formInfo.data.repairType == 2
  ) {
    selectDeptInfo.visible = true
  }
}
// 仓库
function openDepotNameWindow() {
  if (
    formInfo.repairInfoSlot.depotName.disabled &&
    formInfo.data.repairType == 2
  ) {
    selectDepotInfo.visible = true
  }
}
//维保商
function openMaintenanceProviderWindow() {
  if (!disabledMaintenanceName.value) {
    selectMaintenanceProvider.visible = true
  }
}

// 故障库
function openFault() {
  console.log(formInfo.data)
  seelctFault.value.visible = true
  seelctFault.value.query['repairTypeMult'] = formInfo.data.repairType
  seelctFault.value.query['classifyTypeMult'] = formInfo.data.classifyType
  seelctFault.value.query['classifyTypeValue'] = formInfo.data.classifyTypeValue
  seelctFault.value.query['notAssetRepairTypeMult'] =
    formInfo.data.notAssetRepairType
}

function selectFaultCallback(row) {
  formInfo.data.faultDescribe = row.faultDescribe
  formInfo.data.faultLibraryId = row.id
}
function openAssetResource() {
  //故障部位
  if (!formInfo.data['assetId'] || formInfo.data['assetId'] === -2) {
    proxy.$message({
      type: 'warning',
      duration: 3500,
      message: '请先选择资产',
      showClose: true,
    })
    return
  }
  selectAssetResourceInfo.value.visible = true
  selectAssetResourceInfo.value.query.assetId = formInfo.data['assetId']
}
function SelectAssetResourceCallBack(data) {
  if (data && data.length) {
    let resourceName = data.map((item) => item.resourceName)
    formInfo.data.faultPart =
      resourceName && resourceName.length ? resourceName.toString() : ''
  } else {
    formInfo.data.faultPart = ''
  }
}
//维保联系人
function openMaintenanceContactsList() {
  if (formInfo.data.maintainChannel == 1) {
    if (!formInfo.data.maintenanceName) {
      proxy.$message({
        type: 'warning',
        duration: 3500,
        message: '请先选择维保商',
        showClose: true,
      })
      return
    }
  }
  selectMaintenanceContactsInfo.query.orgId =
    formInfo.data.maintenanceId === -2 ? '' : formInfo.data.maintenanceId
  selectMaintenanceContactsInfo.query.assetId =
    formInfo.data.assetId === -2 ? '' : formInfo.data.assetId
  selectMaintenanceContactsInfo.query.deptId =
    formInfo.data.useDeptId === -2 ? '' : formInfo.data.useDeptId
  selectMaintenanceContactsInfo.query.depotId =
    formInfo.data.depotId === -2 ? '' : formInfo.data.depotId
  selectMaintenanceContactsInfo.query.assetClassifyId =
    formInfo.data.classifyType === -2 ? '' : formInfo.data.classifyType
  selectMaintenanceContactsInfo.query.notAssetRepairType =
    formInfo.data.notAssetRepairType === -2
      ? ''
      : formInfo.data.notAssetRepairType
  selectMaintenanceContactsInfo.visible = true
}
//维保商
function selectMaintenanceProviderCallback(row) {
  if (row) {
    formInfo.data['maintenanceName'] = row.maintenanceName
    formInfo.data['maintenanceId'] = row.maintenanceId
    formInfo.data['maintenanceUser'] = ''
    formInfo.data['maintenanceUserName'] = ''
  } else {
    formInfo.data['maintenanceName'] = ''
    formInfo.data['maintenanceId'] = ''
    formInfo.data['maintenanceUser'] = ''
    formInfo.data['maintenanceUserName'] = ''
  }
}
//维保联系人
function selectMaintenanceContactsCallBack(row) {
  if (row) {
    formInfo.data['maintenanceUserName'] = row.name
    formInfo.data['maintenanceUser'] = row.userId
    formInfo.data['maintenanceUserTel'] = row.tel
  } else {
    formInfo.data['maintenanceUserName'] = ''
    formInfo.data['maintenanceUser'] = -2
    formInfo.data['maintenanceUserTel'] = ''
  }
}
function save() {
  let userIds = []
  //查询维修人员
  getMaintenanceGroupUserCheckAll().then((res) => {
    if (res.success && res.data != null) {
      res.data.map((value) => {
        if (value.userId != undefined) {
          userIds.push(value.userId)
        }
      })
    }

    proxy.$fn.checkForm(formRefs.value).then(() => {
      let api
      const params = {
        ...formInfo.data,
      }
      // 非资产卡片
      if (params.repairType == 2) {
        if (!params.useDeptName) {
          proxy.$message.warning('非资产卡片报修时需选择使用部门！')
          return
        }
      }

      if (params.maintainChannel == 1 && !params.maintenanceName) {
        proxy.$message.warning(
          '该设备未配置维保商，无法进行平台报修，请选择院内维修或联系管理人员添加维保商！'
        )
        return
      } else {
        let type
        api = props.id ? updateRepairOrder : createRepairOrder
        type = props.id ? 'update' : 'create'
        proxy
          .$handleAPI(type, api, params)
          .then((res) => {
            if (res.success) {
              showDialog.value = false
              emit('returnModify', false)
            }
            // else if (props.flowFormType) {
            //   getDetails(props.id)
            //   router.go(-1)
            // }
          })
          .catch(() => {})
      }
    })
  })
}
function saveAndSubmit(obj = {}) {
  let userIds = []
  //查询维修人员
  getMaintenanceGroupUserCheckAll().then((res) => {
    if (res.success && res.data != null) {
      res.data.map((value) => {
        if (value.userId != undefined) {
          userIds.push(value.userId)
        }
      })
    }

    proxy.$fn.checkForm(formRefs.value).then(() => {
      let api
      const params = {
        ...formInfo.data,
      }
      // 非资产卡片
      if (params.repairType == 2) {
        if (!params.useDeptName) {
          proxy.$message.warning('非资产卡片报修时需选择使用部门！')
          return
        }
      }
      if (params.maintainChannel == 1 && !params.maintenanceName) {
        proxy.$message.warning(
          '该设备未配置维保商，无法进行平台报修，请选择院内维修或联系管理人员添加维保商！'
        )
        return
      } else {
        let type
        api = submitRepairOrder
        type = props.id ? 'update' : 'create'
        const flowParams = {
          orderData: params,
          // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
          flowTaskCommentDto: { approvalType: 'submit' },
          processDefinitionKey: 'repairApply',
          processInstanceId: obj.processInstanceId,
          taskId: obj.taskId,
        }
        proxy
          .$handleAPI(type, api, flowParams)
          .then((res) => {
            if (res.success) {
              showDialog.value = false
              emit('returnModify', false)
            }
          })
          .catch(() => {})
      }
    })
  })
}
function returnBack() {
  showDialog.value = false
  emit('returnBack', false)
}
function getDetails(id) {
  getRepairOrderById(id).then((res) => {
    if (res && res.success) {
      if (res.data.maintainChannel == 2) {
        _.find(formInfo.baseInfoFieldList, [
          'value',
          'maintainChannel',
        ]).show = false
        _.find(formInfo.repairInfoFieldList, [
          'value',
          'maintenanceName',
        ]).show = false
      }
      if (res.data.assetStatus === 1) {
        showFieldListItem(true, 'useDeptName')
        showFieldListItem(false, 'depotName')
      } else if (res.data.assetStatus === 3) {
        showFieldListItem(false, 'useDeptName')
        showFieldListItem(true, 'depotName')
      }
      formInfo.data = res.data
      if (res.data.repairType === 2) {
        showFieldListItem(false, 'classifyTypeValue')
        showFieldListItem(true, 'notAssetRepairType')
        attrFieldListItem('show', false, 'assetCode')
        attrFieldListItem('show', true, 'useDeptName')
        // attrFieldListItem('show', true, 'depotName')
        attrFieldListItem('disabled', false, 'useDeptName')
        let assetName = {
          disabled: false,
          placeholder: '请输入资产',
        }
        let assetNameRule = [
          {
            required: true,
            message: '请输入资产',
            trigger: 'blur',
          },
        ]
        formInfo.repairInfoSlot['assetName'] = assetName
        formInfo.repairInfoRules['assetName'] = assetNameRule
      }
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  getFlowFormInfo,
  save,
  saveAndSubmit,
})
</script>

<style scoped>
.i-more-disabled {
  cursor: not-allowed;
}
.i-more {
  background-color: #ffffff;
  cursor: pointer;
  height: 26px;
}
</style>
